package com.JavaWeb.dao.user;

import com.JavaWeb.dao.BaseDao;
import com.JavaWeb.pojo.User;
import com.mysql.cj.util.StringUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao{
    //得到要登录的账户
    public User getLoginUser(Connection connection, String userCode) {

        PreparedStatement pstm=null;
        ResultSet rs=null;
        User user=null;

        if(connection!=null){
            //编写SQL语句
            String sql="select * from smbms_user where userCode=?";
            Object[] params={userCode};
            try {
                rs = (ResultSet) BaseDao.execute(connection, pstm, rs, sql, params);
                if(rs.next()){
                    user=new User();//封装到一个用户里面（存值）
                    user.setId(rs.getInt("id"));
                    user.setUserCode(rs.getString("userCode"));
                    user.setUserName(rs.getString("userName"));
                    user.setUserPassword(rs.getString("userPassword"));
                    user.setGender(rs.getInt("gender"));
                    user.setBirthday(rs.getDate("birthday"));
                    user.setPhone(rs.getString("phone"));
                    user.setAddress(rs.getString("address"));
                    user.setUserRole(rs.getInt("userRole"));
                    user.setCreatedBy(rs.getInt("createdBy"));
                    user.setCreationDate(rs.getTimestamp("creationDate"));
                    user.setModifyBy(rs.getInt("modifyBy"));
                    user.setModifyDate(rs.getTimestamp("modifyDate"));
                }
                //关闭连接
              BaseDao.closeResource(null,pstm,rs);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return user;
    }

    //修改用户当前密码
    public int updatePwd(Connection connection, int id, String password) throws SQLException {
        PreparedStatement pstm=null;
        int execute=0;
        if (connection!=null){
            String sql="update smbms_user set userPassword =? where id=?";
            Object params[]={password,id};
            BaseDao.execute(connection,pstm,sql,params);
            BaseDao.closeResource(null,pstm,null);
        }
        return execute;
    }

    //根据用户名或者角色名查询用户总数
    public int getUserCount(Connection connection, String username, int userRole) throws SQLException {
        PreparedStatement pstm=null;
        ResultSet rs = null;
        int count = 0;

        if(connection!=null){
//            用StringBuffer  拼接字符
            StringBuffer sql = new StringBuffer();
            sql.append("select count(1) as count from smbms_user u,smbms_role r where u.userRole = r.id");

            ArrayList<Object> list = new ArrayList<Object>();//存放参数

            if(!StringUtils.isNullOrEmpty(username)){//如果用户名不为空
                    sql.append(" and u.userName LIKE ?");
                    list.add("%"+username+"%");//数组下标index：0
                }
                if(userRole>0){//如果用户角色大于0
                    sql.append(" and u.userRole=?");
                    list.add(userRole);//数组下标index：1
                }
                //list转换为数组
            Object[] params = list.toArray();

            System.out.println("UserDaoImpl->getUserCount:"+sql.toString());//最后完整的sql语句

            rs= (ResultSet) BaseDao.execute(connection,pstm,rs, sql.toString(), params);

            if(rs.next()){
                count = rs.getInt("count");
            }
            BaseDao.closeResource(null, pstm, rs);
        }
        return count;

    }

    // 通过条件查询-用户表记录数
    public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws Exception {
        PreparedStatement pstm=null;
        ResultSet rs = null;
        int count = 0;
        List<User> userList = new ArrayList<User>();

        if(connection!=null){
//            用StringBuffer  拼接字符
            StringBuffer sql = new StringBuffer();
//            sql.append("select count(1) as count from smbms_user u,smbms_role r where u.userRole = r.id");
            sql.append("select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.userRole = r.id");

            ArrayList<Object> list = new ArrayList<Object>();//存放参数

            if(!StringUtils.isNullOrEmpty(userName)){//如果用户名不为空
                sql.append(" and u.userName LIKE ?");
                list.add("%"+userName+"%");//数组下标index：0
            }
            if(userRole>0){//如果用户角色大于0
                sql.append(" and u.userRole=?");
                list.add(userRole);//数组下标index：1
            }
        //分页 order by creationDate DESC limit  记录开始位置，记录多少条
            sql.append(" order by creationDate DESC limit ?,?");//拼接sql语句
            currentPageNo = (currentPageNo - 1) * pageSize;
            //添加到list集合中
            list.add(currentPageNo);//index :2
            list.add(pageSize);//index:3

            //list集合转化数组
            Object[] params = list.toArray();
            System.out.println("sql-->"+sql.toString());//sql最后拼接的语句
            rs =(ResultSet)BaseDao.execute(connection, pstm, rs, sql.toString(), params);
            while(rs.next()){
                User _user = new User();
                _user.setId(rs.getInt("id"));
                _user.setUserCode(rs.getString("userCode"));
                _user.setUserName(rs.getString("userName"));
                _user.setGender(rs.getInt("gender"));
                _user.setBirthday(rs.getDate("birthday"));
                _user.setPhone(rs.getString("phone"));
                _user.setUserRole(rs.getInt("userRole"));
                _user.setUserRoleName(rs.getString("userRoleName"));
                userList.add(_user);
            }
            BaseDao.closeResource(null, pstm, rs);
        }
        return userList;
        }

        //增加用户
    @Override
    public int add(Connection connection, User user) {
        PreparedStatement pstm = null;
        int updateRows = 0;
        if(null != connection){
            String sql = "insert into smbms_user (userCode,userName,userPassword," +
                    "userRole,gender,birthday,phone,address,creationDate,createdBy) " +
                    "values(?,?,?,?,?,?,?,?,?,?)";
            Object[] params = {user.getUserCode(),user.getUserName(),user.getUserPassword(),
                    user.getUserRole(),user.getGender(),user.getBirthday(),
                    user.getPhone(),user.getAddress(),user.getCreationDate(),user.getCreatedBy()};
            try {
                updateRows = BaseDao.execute(connection, pstm, sql, params);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            BaseDao.closeResource(null, pstm, null);
        }
        return updateRows;
    }
    //通过userId删除user
    @Override
    public int deleteUserById(Connection connection, Integer delId) throws Exception {
        PreparedStatement pstm = null;
        int flag = 0;
        if(null != connection){
            String sql = "delete from smbms_user where id=?";
            Object[] params = {delId};
            flag = BaseDao.execute(connection, pstm, sql, params);
            BaseDao.closeResource(null, pstm, null);
        }
        return flag;
    }
    //通过userId获取user
    @Override
    public User getUserById(Connection connection, String id) throws Exception {
        User user = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        if(null != connection){
            String sql = "select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.id=? and u.userRole = r.id";
            Object[] params = {id};
            rs = (ResultSet) BaseDao.execute(connection, pstm, rs, sql, params);
            if(rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUserCode(rs.getString("userCode"));
                user.setUserName(rs.getString("userName"));
                user.setUserPassword(rs.getString("userPassword"));
                user.setGender(rs.getInt("gender"));
                user.setBirthday(rs.getDate("birthday"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                user.setUserRole(rs.getInt("userRole"));
                user.setCreatedBy(rs.getInt("createdBy"));
                user.setCreationDate(rs.getTimestamp("creationDate"));
                user.setModifyBy(rs.getInt("modifyBy"));
                user.setModifyDate(rs.getTimestamp("modifyDate"));
                user.setUserRoleName(rs.getString("userRoleName"));
            }
            BaseDao.closeResource(null, pstm, rs);
        }
        return user;
    }
    //修改用户信息
    @Override
    public int modify(Connection connection, User user) throws Exception {
        int flag = 0;
        PreparedStatement pstm = null;
        if(null != connection){
            String sql = "update smbms_user set userName=?,"+
                    "gender=?,birthday=?,phone=?,address=?,userRole=?,modifyBy=?,modifyDate=? where id = ? ";
            Object[] params = {user.getUserName(),user.getGender(),user.getBirthday(),
                    user.getPhone(),user.getAddress(),user.getUserRole(),user.getModifyBy(),
                    user.getModifyDate(),user.getId()};
            flag = BaseDao.execute(connection, pstm, sql, params);
            BaseDao.closeResource(null, pstm, null);
        }
        return flag;
    }
}
